package com.basic.business.order.service.impl;

import com.basic.business.order.mapper.ITOrdersDetailMapper;
import com.basic.business.order.mapper.ITOrdersMainMapper;
import com.basic.business.order.mapper.ITOrdersMergeMapper;
import com.basic.business.order.domain.TOrdersMain;
import com.basic.business.order.service.ITOrdersMainService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 订单主表服务实现类
 *
 * @author zhaoxy_jn@163.com
 */
@Service
public class TOrdersMainServiceImpl implements ITOrdersMainService {

    @Resource
    private ITOrdersMainMapper itOrdersMainMapper;

    @Resource
    private ITOrdersDetailMapper itOrdersDetailMapper;

    @Resource
    private ITOrdersMergeMapper itOrdersMergeMapper;

    @Override
    public Long getLastUpdTime() {
        return itOrdersMainMapper.getLastUpdTime();
    }

    @Override
    public int delByUpdTime(Long zeroTimestamp) {
        // 先查询出来，再删除
        List<Long> sids = itOrdersMainMapper.getListByUpdTime(zeroTimestamp);
        // 删除主订单信息
        int cnt = itOrdersMainMapper.delByUpdTime(zeroTimestamp);
        if (cnt > 0) {
            // 删除明细信息
            itOrdersDetailMapper.delBySids(sids);
            // 删除合并信息
            itOrdersMergeMapper.delBySids(sids);
        }
        return cnt;
    }

    @Transactional
    @Override
    public int batchInsertOrUpdate(List<TOrdersMain> ordersMains) {
        int cnt = itOrdersMainMapper.batchInsertOrUpdate(ordersMains);
        if (cnt > 0) {
            ordersMains.forEach(ordersMain -> {
                itOrdersDetailMapper.batchInsertOrUpdate(ordersMain.getDetailList());
                if (!ordersMain.getMergeList().isEmpty()){
                    itOrdersMergeMapper.batchInsertOrUpdate(ordersMain.getMergeList());
                }
            });
        }
        return cnt;
    }

    @Override
    public int updateAutoProcessStatus(Long mainSid, String processStatus) {
        return itOrdersMainMapper.updateAutoProcessStatus(mainSid, processStatus);
    }
}
